package com.jietuo.class03;

import java.util.Arrays;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2024/3/3
 * @description: 归并排序
 */
public class Code01_MergeSort {

    public static void main(String[] args) {

        int[] arr = new int[]{2, 5, 7, 2, 5, 67, 7, 9};
        System.out.println(Arrays.toString(arr));
        mergeSort(arr);
        System.out.println(Arrays.toString(arr));

    }

    public static void mergeSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        // 开始递归
        process(arr, 0, arr.length - 1);
    }

    public static void process(int[] arr, int left, int right) {
        if (left == right) {
            return;
        }
        int mid = left + ((right - left) >> 1);
        // 先排序左边的，再排序右边的，然后进行merge
//        int mid = (left + right) / 2;
        process(arr, left, mid);
        process(arr, mid + 1, right);
        merge1(arr, left, mid, right);
    }

    private static void merge(int[] arr, int left, int mid, int right) {
        int leftIndex = left;
        int rightIndex = mid + 1;
        int helpIndex = 0;
        int[] help = new int[right - left + 1];
        while (leftIndex <= mid && rightIndex <= right) {
            if (arr[leftIndex] <= arr[rightIndex]) {
                help[helpIndex] = arr[leftIndex];
                leftIndex++;
                helpIndex++;
            } else if (arr[leftIndex] > arr[rightIndex]) {
                help[helpIndex] = arr[rightIndex];
                rightIndex++;
                helpIndex++;
            }
        }
        while (leftIndex <= mid) {
            help[helpIndex] = arr[leftIndex];
            helpIndex++;
            leftIndex++;
        }

        while (rightIndex <= right) {
            help[helpIndex] = arr[rightIndex];
            helpIndex++;
            rightIndex++;
        }

        for (int i = 0; i < help.length; i++) {
            arr[left + i] = help[i];
        }
    }

    private static void merge1(int[] arr, int left, int mid, int right) {
        int leftIndex = left;
        int rightIndex = mid + 1;
        int helpIndex = 0;
        int[] help = new int[right - left + 1];
        while (leftIndex <= mid && rightIndex <= right) {
            help[helpIndex++] = arr[leftIndex] <= arr[rightIndex] ? arr[leftIndex++] : arr[rightIndex++];
        }
        while (leftIndex <= mid) {
            help[helpIndex++] = arr[leftIndex++];
        }
        while (rightIndex <= right) {
            help[helpIndex++] = arr[rightIndex++];
        }

        for (int i = 0; i < help.length; i++) {
            arr[left + i] = help[i];
        }
    }
}
